//
//  RCPopMenuView.m
//  RCsinaMicroBlog
//
//  Created by Mr.Ray on 15/2/1.
//  Copyright (c) 2015年 Ray.peng. All rights reserved.
//

#import "RCPopMenuView.h"

//设置静态变量 避免死亡
static UIWindow *_window;
static UIViewController *_contentVC;
static dismissBlock _dismiss;


@implementation RCPopMenuView


+ (void)popMenuView:(UIView *)fromView content:(UIView *)content dismiss:(dismissBlock)dismiss{
    [self popMenuView:fromView.frame inView:fromView.superview content:content dismiss:dismiss];

}

+ (void)popMenuView:(CGRect)fromRect inView:(UIView *)inView content:(UIView *)content dismiss:(dismissBlock)dismiss{
    //block需要拷贝一下
    _dismiss = [dismiss copy];
    
    //创建window
    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    //window默认是隐藏的
    _window.hidden = NO;
    //设置优先级
    _window.windowLevel = UIWindowLevelAlert;
    //创建蒙版
    UIButton *cover = [[UIButton alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [_window addSubview:cover];
    
    //创建一个view
    UIImageView *imageView = [[UIImageView alloc]init];
    imageView.image = [UIImage imageNamed:@"popover_background"];
    imageView.userInteractionEnabled = YES;
    //设置    // 设置内容的X和Y值(间隙)
    content.x = 15;
    content.y = 18;
    [imageView addSubview:content];
    
    //设置设置菜单容器的frame
    CGFloat imageViewW = CGRectGetMaxX(content.frame) +content.x;
    CGFloat imageViewH = CGRectGetMaxY(content.frame) +content.y;
    imageView.frame = CGRectMake(0, 0, imageViewW, imageViewH);
    
    // 获取需要指向控件的frame, 并且是转换为和蒙版同一个坐标系的frame
    // 将fromView.frame的坐标系 从 fromView.superview  转换为 _window
    CGRect resultFrame = [_window convertRect:fromRect fromView:inView];
    
    //设置image的坐标
    imageView.y = CGRectGetMaxY(resultFrame);
    imageView.centerX = resultFrame.origin.x +(resultFrame.size.width * 0.5);
    
    [cover addSubview:imageView];
}
//调用方法是类方法 那么此方法必须是类方法
+ (void)coverClick:(UIButton *)btn{
    _window = nil;
    _contentVC = nil;
    //点击调用block
    
    if (_dismiss != nil) {
        _dismiss();
        
    }

}

+ (void)popMenuView:(UIView *)fromView contentVc:(UIViewController *)content dismiss:(dismissBlock)dismiss{
    _contentVC = content;
    
    [self popMenuView:fromView content:_contentVC.view dismiss:dismiss];
}

@end
